package com.neutech.controller;

import com.google.gson.Gson;
import com.neutech.dao.OrderService;
import com.neutech.dao.impl.OrderServiceImpl;
import com.neutech.entity.User;
import com.neutech.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/order/create")
public class OrderCreateServlet extends HttpServlet {

    private OrderService orderService = new OrderServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String deliveryAddressId = req.getParameter("deliveryAddressId");
        String[] cartIds = req.getParameterValues("cartId");

        Integer[] ids = new Integer[cartIds.length];
        for (int i = 0; i < cartIds.length; i++) {
            ids[i] = Integer.parseInt(cartIds[i]);
        }

        User user = (User) req.getSession().getAttribute("user");

        ResultVO resultVO = orderService.create(ids, Integer.parseInt(deliveryAddressId), user.getId());

        PrintWriter out = resp.getWriter();
        out.print(new Gson().toJson(resultVO));
        out.close();
    }
}
